export default {
  // 为当前模块开启命名空间
  namespaced: true,
  // 模块的 state 数据
  state: () => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  // 模块的 mutations 方法
  mutations: {
    // 加入购物车方法
    addToCart(state,goods){
      const goodsRes = state.cart.find(item => item.goods_id === goods.goods_id)
      if(!goodsRes){
        state.cart.push(goods)
      } else {
        goodsRes.goods_count++
      }
      this.commit('m_cart/saveLocalData')
    },
    // 数据本地持久化
    saveLocalData(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    // 更新商品选中状态
    updateGoodsState(state,goods){
      const targetObj = state.cart.find(item => item.goods_id === goods.goods_id)
      if(targetObj){
        targetObj.goods_state = goods.goods_state
      }
      this.commit('m_cart/saveLocalData')
    },
    // 商品计数器
    goodsCountChange(state,goods){
      let targetObj = state.cart.find(item => item.goods_id === goods.goods_id)
      if(targetObj){
        targetObj.goods_count = goods.goods_count
      }
      this.commit('m_cart/saveLocalData')
    },
    // 点击删除商品
    delGoodsItem(state,goods_id){
      state.cart = state.cart.filter(item => item.goods_id !== goods_id)
      this.commit('m_cart/saveLocalData')
    },
    // 全选按钮改变赋值
    allBtnChange(state,newType){
      state.cart.forEach(item => item.goods_state = newType)
    }
  },
  // 模块的 getters 属性
  getters: {
    // 购物车商品总数
    total(state){
      return state.cart.reduce((total,item) => total += item.goods_count,0)
    },
     // 结算总数
    checkedCount(state){
      return state.cart.filter(item => item.goods_state).reduce((total,itemm) => total += itemm.goods_count,0)
    },
    // 计算已选择商品的累加和
    checkedPriceSum(state){
      return state.cart.filter(item => item.goods_state)
      .reduce((sum,itemm) => sum += itemm.goods_count * itemm.goods_price ,0)
      .toFixed(2)
    }
  },
}